package com.gitee.gateway.core.db;

import com.gitee.gateway.core.utils.Configuration;
import com.gitee.gateway.core.utils.CryptUtils;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import io.vertx.core.json.JsonObject;
import jodd.bean.BeanUtil;
import org.jdbi.v3.core.HandleConsumer;
import org.jdbi.v3.core.Jdbi;
import org.jdbi.v3.core.extension.ExtensionCallback;
import org.jdbi.v3.core.extension.ExtensionConsumer;
import org.jdbi.v3.core.statement.Slf4JSqlLogger;
import org.jdbi.v3.sqlobject.SqlObjectPlugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.nio.file.NoSuchFileException;
import java.sql.DatabaseMetaData;
import java.util.HashMap;
import java.util.Map;

/**
 * Database connection manager
 */
public class DatabaseManager {

    private final static Logger LOGGER = LoggerFactory.getLogger("[database]");

    private final static String PASSWORD_ENCRYPTION_SECRET_KEY = "@GiteeGW#202309";

    private static HikariDataSource dataSource;
    private static Jdbi jdbi;

    static {
        try {
            JsonObject config = Configuration.loadDatabase();
            String database = config.getString("database");
            JsonObject dbConfig = config.getJsonObject(database);
            dbConfig.put("password", CryptUtils.decrypt(dbConfig.getString("password"), PASSWORD_ENCRYPTION_SECRET_KEY));
            init(dbConfig);
        } catch (NoSuchFileException e) {
            LOGGER.warn("Database configuration file ('config/database.yaml') not found, skipped.");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static boolean testConnection() {
        return jdbi != null;
    }

    /**
     * Initialize database connection
     *
     * @param jsonConfig 数据库配置
     */
    private static void init(JsonObject jsonConfig) {
        Map<String, Object> params = new HashMap<>();
        jsonConfig.forEach(e -> params.put(e.getKey(), e.getValue()));
        HikariConfig config = new HikariConfig();
        params.forEach((k, v) -> BeanUtil.pojo.setProperty(config, k, v));
        dataSource = new HikariDataSource(config);
        initJdbi(dataSource);
        jdbi.useHandle(h -> {
            String name = h.queryMetadata(DatabaseMetaData::getDatabaseProductName);
            String version = h.queryMetadata(DatabaseMetaData::getDatabaseProductVersion);
            String url = h.queryMetadata(DatabaseMetaData::getURL);
            LOGGER.info(String.format("Connected to %s %s (%s)", name, version, url));
        });
    }

    /**
     * configure jdbi
     *
     * @param ds 数据源
     */
    private static void initJdbi(DataSource ds) {
        jdbi = Jdbi.create(ds);
        jdbi.registerArgument(new JsonObjectArgumentFactory());
        jdbi.registerArgument(new JsonArrayArgumentFactory());
        jdbi.setSqlLogger(new Slf4JSqlLogger(LOGGER));
        jdbi.installPlugin(new SqlObjectPlugin());
    }

    public static <E> E onDemand(Class<E> daoClass) {
        return jdbi.onDemand(daoClass);
    }

    public static <E, X extends Exception> void useExtension(Class<E> extensionType, ExtensionConsumer<E, X> callback) throws X {
        jdbi.useExtension(extensionType, callback);
    }

    public static <R, E, X extends Exception> R withExtension(Class<E> extensionType, ExtensionCallback<R, E, X> callback) throws X {
        return jdbi.withExtension(extensionType, callback);
    }

    public static <X extends Exception> void useHandle(final HandleConsumer<X> consumer) throws X {
        jdbi.withHandle(consumer.asCallback());
    }

    /**
     * 关闭连接池
     */
    public synchronized static void close() {
        if (dataSource != null && !dataSource.isClosed())
            dataSource.close();
    }

}
